// <editor-fold defaultstate="collapsed" desc="GNU GPLv3 Header">
/*
 * File:   ChunkDataPCMByte.c
 *
 * Copyright (C) 2013 Robert Antoni Buj Gelonch <rbuj@uoc.edu>
 * Copyright (C) 2013 David Megias Jimenez <dmegias@uoc.edu>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
// </editor-fold>

#include "../ChunkDataNonPCMByte.h"

/**
 *
 * @param file
 * @param channels
 * @return
 */
ChunkDataNonPCMByte* readChunkDataNonPCMByte(FILE* file, int channels) {
    int i, j, lenght;
    ChunkDataNonPCMByte* chunkDataNonPCMByte = malloc(sizeof (ChunkDataNonPCMByte));
    chunkDataNonPCMByte->dataNonPCM = readChunkDataNonPCM(file);
    lenght = (chunkDataNonPCMByte->dataNonPCM->data->ck->size) / channels;
    chunkDataNonPCMByte->samples = malloc(channels * lenght * sizeof (short int));
    for (i = 0; i < lenght; i++) {
        for (j = 0; j < channels; j++) {
            readByteLE(file, &chunkDataNonPCMByte->samples[(lenght * j) + i]);
        }
    }
    return chunkDataNonPCMByte;
}

/**
 *
 * @param chunkDataNonPCMByte
 */
void freeChunkDataNonPCMByte(ChunkDataNonPCMByte* chunkDataNonPCMByte) {
    freeChunkDataNonPCM(chunkDataNonPCMByte->dataNonPCM);
    free(chunkDataNonPCMByte->samples);
    free(chunkDataNonPCMByte);
}

/**
 *
 * @param chunkDataNonPCMByte
 * @param channels
 * @param file
 */
void writeChunkDataNonPCMByte(ChunkDataNonPCMByte* chunkDataNonPCMByte,
        int channels,
        FILE* file) {
    int i, j, lenght;
    writeChunkDataNonPCM(chunkDataNonPCMByte->dataNonPCM, file);
    lenght = (chunkDataNonPCMByte->dataNonPCM->data->ck->size) / channels;
    for (i = 0; i < lenght; i++) {
        for (j = 0; j < channels; j++) {
            writeByteLE(&chunkDataNonPCMByte->samples[(lenght * j) + i], file);
        }
    }
}

